<%@page import="org.ifilm.model.User"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<title>Messages</title>
		<link rel="icon" type="image/png" href="/film/img/favicon.ico">
		<link href="/film/bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen"/>
		<script src="/film/js/jquery.js"></script>
	    <script src="/film/bootstrap/js/bootstrap.min.js"></script>
	    <script src="/film/bootstrap/js/typeahead.js"></script>
	    <style>
	      	body {
	        	padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
	      	}
	    </style>
	</head>
	<body>
		<jsp:include page="navigationBar.jsp"/>
		<div class="container">
			 <div class="content-container">
			 	<button id="inbox" class="btn">Inbox</button>
			 	<a href="#myModal" style="color:#333;" data-toggle="modal"><button class="btn">New Message</button></a>
			 	<div id="content">
			 		<table class="table table-striped">
						<th>Between</th>
						<th>Subject</th>
						<c:forEach var="subject" items="${messageSubjects}">
							<tr class="message" style="cursor:pointer;" bgcolor="gray" sid="${subject.id}">
								<td>${subject.sender.name} ${subject.sender.surname} - ${subject.receiver.name} ${subject.receiver.surname}</td>
								<td>${subject.subject}</td>
							</tr>
							<tr></tr>
						</c:forEach>
					</table>
			 	</div>
			 	<div id="messagecontent" style="display:none">
			 	</div>
			 	
			 	<!-- Modal -->
				<div id="myModal" style="width:700px;" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
				  	<div class="modal-header">
				    	<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
				    	<h3 id="myModalLabel">Send Message</h3>
				 	</div>
				  	<div class="modal-body">
				  		<table>
				  			<tr>
					  			<td>To : </td>
					  			<td><input type="text" id="to" class="typeahead"/></td>
					  		</tr>
				  			<tr>
					  			<td>Subject : </td>
					  			<td><input type="text" id="subject"/></td>
					  		</tr>
					  		<tr>
						    	<td>Message : </td>
					    		<td><textarea id="messageText" rows="6" style="width: 500px;"></textarea></td>
				    		</tr>
			    		</table>
				  	</div>
				  	<div class="modal-footer">
				    	<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
				    	<button onclick="sendMessage();" class="btn btn-primary">Send</button>
				  	</div>
				</div>
				
				<!--replyModal -->
				<div id="replyModal" style="width:700px;" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
				  	<div class="modal-header">
				    	<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
				    	<h3 id="myModalLabel">Send Message</h3>
				 	</div>
				  	<div class="modal-body">
				  		<table>
					  		<tr>
						    	<td>Message : </td>
					    		<td><textarea id="replyText" rows="6" style="width: 500px;"></textarea></td>
				    		</tr>
			    		</table>
				  	</div>
				  	<div class="modal-footer">
				    	<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
				    	<button onclick="sendReply();" class="btn btn-primary">Send</button>
				  	</div>
				</div>
			</div>
			
			<input type="hidden" id="subjectId" val="">
		</div>
	</body>
	<script type="text/javascript">
		var messageReceiverId = null;
		$('#to').typeahead({
			property: "name",
		    source: function (typeahead, query) {
		    	var options = {page : 1, max : 5, searchText : typeahead.query};
		        return $.get('/film/user/getFollowing.do', options, function (data) {
		        	if (data && data.users) {
		        		var names = new Array();
		        		$.each(data.users, function(key, cur) {
		        			if (cur.name && cur.surname) {
		        				names.push({name : cur.name + " " + cur.surname, id : cur.id})
		        			}
		        		});
		        		
		        		return typeahead.process(names);
		        	}
		        });
		    },
			onselect: function (obj) {
				if (obj.id)	{
					messageReceiverId = obj.id;
				}
		    }
		});
		
		$(".message").click(function() {
			$.ajax("/film/message/getMessageSubject.do?messageSubjectId=" + $(this).attr("sid")).done(function(data) {
				if (data.subject) {
					var table = $('<table class="table table-striped"></table');
					var th = $("<th>Sender</th><th>Message</th>");
					table.append(th);
					
					$.each(data.subject.messages.sort(sortById), function(key, cur) {
						if (cur.receiverId == <%=((User)session.getAttribute("user")).getId()%>) {
							if (data.subject.sender.id == cur.senderId) {
								$tr = $("<tr><td>" + data.subject.sender.name + " " + data.subject.sender.surname + "</td><td>" + cur.message + "</td></tr>");
							} else {
								$tr = $("<tr><td>" + data.subject.receiver.name + " " + data.subject.receiver.surname + "</td><td>" + cur.message + "</td></tr>");
							}
							
							messageReceiverId = cur.senderId;
						} else {
							if (data.subject.sender.id == cur.senderId) {
								$tr = $("<tr><td>" + data.subject.sender.name + " " + data.subject.sender.surname + "</td><td>" + cur.message + "</td></tr>");
							} else {
								$tr = $("<tr><td>" + data.subject.receiver.name + " " + data.subject.receiver.surname + "</td><td>" + cur.message + "</td></tr>");
							}
							
							messageReceiverId = cur.receiverId;
						}
						
						table.append($tr);
					});
					
					$("#subjectId").val(data.subject.id);
					$("#messagecontent").append(table).append("<a href='#replyModal' style='color:#333;' class='pull-right' data-toggle='modal'><button id='reply' class='btn'>Reply</button></a>");
					$("#content").hide();
					$("#messagecontent").show();
				}
			});
		});
		
		function sortById (a, b) {
		  	var aId = a.id;
		  	var bId = b.id; 
		  	return ((aId < bId) ? -1 : ((aId > bId) ? 1 : 0));
		}
		
		function sendReply() {
			var replyText = $("#replyText").val();
			$.ajax("/film/message/createMessage.do?receiverId=" + messageReceiverId + 
					"&message=" + replyText + "&messageSubjectId=" + $("#subjectId").val()).done(function(data) {
				if (data.status == "success") {
					$('#replyModal').modal('hide');
					$("#replyText").val("");
				}
			});
		};
		
		function sendMessage() {
			var messageText = $("#messageText").val();
			$.ajax("/film/message/createMessage.do?receiverId=" + messageReceiverId + 
					"&message=" + messageText + "&subject=" + $("#subject").val()).done(function(data) {
				if (data.status == "success") {
					$('#myModal').modal('hide');
					$("#messageText").val("");
				}
			});
		};
		
		$("#inbox").click(function() {
			$("#messagecontent").hide();
			$("#content").show();
			$("#messagecontent").html("");
		});
	</script>
	<script src="/film/js/commonScripts.js"></script>
</html>